package com.common.pullToRefresh.internal;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.res.ColorStateList;
import android.content.res.TypedArray;
import android.graphics.Typeface;
import android.graphics.drawable.AnimationDrawable;
import android.graphics.drawable.Drawable;
import android.text.TextUtils;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Interpolator;
import android.view.animation.LinearInterpolator;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.common.StarAppConfig;
import com.common.StarAppConst;
import com.common.pullToRefresh.PullToRefreshBase.Mode;
import com.common.pullToRefresh.PullToRefreshBase.Orientation;
import com.common.utils.StarAppUtils;
import com.handmark.pulltorefresh.library.ILoadingLayout;
import com.handmark.pulltorefresh.library.ResourceUtil;
import com.handmark.pulltorefresh.library.internal.Utils;
import com.handmark.pulltorefresh.library.internal.ViewCompat;
import com.starappallcommon.R;

@SuppressLint("ViewConstructor")
public abstract class ExtLoadingLayout extends FrameLayout implements ILoadingLayout {

	static final String LOG_TAG = "PullToRefresh-LoadingLayout";

	static final Interpolator ANIMATION_INTERPOLATOR = new LinearInterpolator();

	private FrameLayout mInnerLayout;

	protected final ImageView mHeaderImage;
	protected final ProgressBar mHeaderProgress;

	private boolean mUseIntrinsicAnimation;

	private final TextView mHeaderText;
	private final TextView mSubHeaderText;
	private final TextView mSubHeaderTitle;

	protected final Mode mMode;
	protected final Orientation mScrollDirection;

	private CharSequence mPullLabel;
	private CharSequence mRefreshingLabel;
	private CharSequence mReleaseLabel;

	public ExtLoadingLayout(Context context, final Mode mode, final Orientation scrollDirection, TypedArray attrs) {
		super(context);
		mMode = mode;
		mScrollDirection = scrollDirection;

		switch (scrollDirection) {
			case HORIZONTAL:
				LayoutInflater.from(context).inflate(ResourceUtil.getLayoutId(context, "pull_to_refresh_custom_header_horizontal"), this);
				break;
			case VERTICAL:
			default:
				LayoutInflater.from(context).inflate(R.layout.pull_to_refresh_custom_header, this);
				break;
		}

		mInnerLayout = (FrameLayout) findViewById(R.id.fl_inner);
		mHeaderText = (TextView) mInnerLayout.findViewById(R.id.pull_to_refresh_text);
		mHeaderProgress = (ProgressBar) mInnerLayout.findViewById(R.id.pull_to_refresh_progress);
		mSubHeaderText = (TextView) mInnerLayout.findViewById(R.id.pull_to_refresh_sub_text);
		mSubHeaderTitle = (TextView) mInnerLayout.findViewById(R.id.pull_to_refresh_sub_title);
		mHeaderImage = (ImageView) mInnerLayout.findViewById(R.id.pull_to_refresh_image);
		//字体
		setViewTypeFace(mHeaderText, false);
        setViewTypeFace(mSubHeaderText, false);
        setViewTypeFace(mSubHeaderTitle, false);
        
		FrameLayout.LayoutParams lp = (FrameLayout.LayoutParams) mInnerLayout.getLayoutParams();

		switch (mode) {
			case PULL_FROM_END:
				lp.gravity = scrollDirection == Orientation.VERTICAL ? Gravity.TOP : Gravity.LEFT;

				// Load in labels
				mPullLabel = context.getString(ResourceUtil.getStringId(context, "pull_to_refresh_from_bottom_pull_label"));
				mRefreshingLabel = context.getString(ResourceUtil.getStringId(context, "pull_to_refresh_from_bottom_refreshing_label"));
				mReleaseLabel = context.getString(ResourceUtil.getStringId(context, "pull_to_refresh_from_bottom_release_label"));
				break;

			case PULL_FROM_START:
			default:
				lp.gravity = scrollDirection == Orientation.VERTICAL ? Gravity.BOTTOM : Gravity.RIGHT;

				// Load in labels
				mPullLabel = context.getString(ResourceUtil.getStringId(context, "pull_to_refresh_pull_label"));
				mRefreshingLabel = context.getString(ResourceUtil.getStringId(context, "pull_to_refresh_refreshing_label"));
				mReleaseLabel = context.getString(ResourceUtil.getStringId(context, "pull_to_refresh_release_label"));
				break;
		}

		if (attrs.hasValue(ResourceUtil.getStyleId(context, "PullToRefresh_ptrHeaderBackground"))) {
			Drawable background = attrs.getDrawable(ResourceUtil.getStyleId(context, "PullToRefresh_ptrHeaderBackground"));
			if (null != background) {
				ViewCompat.setBackground(this, background);
			}
		}

		if (attrs.hasValue(ResourceUtil.getStyleId(context, "PullToRefresh_ptrHeaderTextAppearance"))) {
			TypedValue styleID = new TypedValue();
			attrs.getValue(ResourceUtil.getStyleId(context, "PullToRefresh_ptrHeaderTextAppearance"), styleID);
			setTextAppearance(styleID.data);
		}
		if (attrs.hasValue(ResourceUtil.getStyleId(context, "PullToRefresh_ptrSubHeaderTextAppearance"))) {
			TypedValue styleID = new TypedValue();
			attrs.getValue(ResourceUtil.getStyleId(context, "PullToRefresh_ptrSubHeaderTextAppearance"), styleID);
			setSubTextAppearance(styleID.data);
		}

		// Text Color attrs need to be set after TextAppearance attrs
		if (attrs.hasValue(ResourceUtil.getStyleId(context, "PullToRefresh_ptrHeaderTextColor"))) {
			ColorStateList colors = attrs.getColorStateList(ResourceUtil.getStyleId(context, "PullToRefresh_ptrHeaderTextColor"));
			if (null != colors) {
				setTextColor(colors);
			}
		}
		if (attrs.hasValue(ResourceUtil.getStyleId(context, "PullToRefresh_ptrHeaderSubTextColor"))) {
			ColorStateList colors = attrs.getColorStateList(ResourceUtil.getStyleId(context, "PullToRefresh_ptrHeaderSubTextColor"));
			if (null != colors) {
				setSubTextColor(colors);
			}
		}

		// Try and get defined drawable from Attrs
		Drawable imageDrawable = null;
		if (attrs.hasValue(ResourceUtil.getStyleId(context, "PullToRefresh_ptrDrawable"))) {
			imageDrawable = attrs.getDrawable(ResourceUtil.getStyleId(context, "PullToRefresh_ptrDrawable"));
		}

		// Check Specific Drawable from Attrs, these overrite the generic
		// drawable attr above
		switch (mode) {
			case PULL_FROM_START:
			default:
				if (attrs.hasValue(ResourceUtil.getStyleId(context, "PullToRefresh_ptrDrawableStart"))) {
					imageDrawable = attrs.getDrawable(ResourceUtil.getStyleId(context, "PullToRefresh_ptrDrawableStart"));
				} else if (attrs.hasValue(ResourceUtil.getStyleId(context, "PullToRefresh_ptrDrawableTop"))) {
					Utils.warnDeprecation("ptrDrawableTop", "ptrDrawableStart");
					imageDrawable = attrs.getDrawable(ResourceUtil.getStyleId(context, "PullToRefresh_ptrDrawableTop"));
				}
				break;

			case PULL_FROM_END:
				if (attrs.hasValue(ResourceUtil.getStyleId(context, "PullToRefresh_ptrDrawableEnd"))) {
					imageDrawable = attrs.getDrawable(ResourceUtil.getStyleId(context, "PullToRefresh_ptrDrawableEnd"));
				} else if (attrs.hasValue(ResourceUtil.getStyleId(context, "PullToRefresh_ptrDrawableBottom"))) {
					Utils.warnDeprecation("ptrDrawableBottom", "ptrDrawableEnd");
					imageDrawable = attrs.getDrawable(ResourceUtil.getStyleId(context, "PullToRefresh_ptrDrawableBottom"));
				}
				break;
		}

		// If we don't have a user defined drawable, load the default
		if (null == imageDrawable) {
			imageDrawable = context.getResources().getDrawable(getDefaultDrawableResId());
		}

		// Set Drawable, and save width/height
		setLoadingDrawable(imageDrawable);

		reset();
	}

	/**
     * 设置视图的字体
     * 
     * <br>
     * Created 2014-7-30 下午6:59:56
     * 
     * @param view
     *            视图对象
     * @param isBold
     *            是否粗体
     * @author : HuangYK
     */
    public static void setViewTypeFace(TextView view, boolean isBold) {
        if (view == null) {
            return;
        }
        StarAppUtils.setViewTypeFace(view, isBold);
//        view.setTypeface(StarAppConst.getInstance().getLTXTypeface());
//        if (isBold) {
//            view.getPaint().setFakeBoldText(true);
//        }
    }
	public final void setHeight(int height) {
		ViewGroup.LayoutParams lp = (ViewGroup.LayoutParams) getLayoutParams();
		lp.height = height;
		requestLayout();
	}

	public final void setWidth(int width) {
		ViewGroup.LayoutParams lp = (ViewGroup.LayoutParams) getLayoutParams();
		lp.width = width;
		requestLayout();
	}

	public final int getContentSize() {
		switch (mScrollDirection) {
			case HORIZONTAL:
				return mInnerLayout.getWidth();
			case VERTICAL:
			default:
				return mInnerLayout.getHeight();
		}
	}

	public final void hideAllViews() {
		if (View.VISIBLE == mHeaderText.getVisibility()) {
			mHeaderText.setVisibility(View.INVISIBLE);
		}
		if (View.VISIBLE == mHeaderProgress.getVisibility()) {
			mHeaderProgress.setVisibility(View.INVISIBLE);
		}
		if (View.VISIBLE == mHeaderImage.getVisibility()) {
			mHeaderImage.setVisibility(View.INVISIBLE);
		}
		if (View.VISIBLE == mSubHeaderText.getVisibility()) {
			mSubHeaderText.setVisibility(View.INVISIBLE);
		}
		if (View.VISIBLE == mSubHeaderTitle.getVisibility()) {
		    mSubHeaderTitle.setVisibility(View.INVISIBLE);
        }
	}

	public final void onPull(float scaleOfLayout) {
		if (!mUseIntrinsicAnimation) {
			onPullImpl(scaleOfLayout);
		}
	}

	public final void pullToRefresh() {
		if (null != mHeaderText) {
			mHeaderText.setText(mPullLabel);
		}

		// Now call the callback
//		pullToRefreshImpl();
		mHeaderProgress.setVisibility(View.INVISIBLE);
	}

	public final void refreshing() {
		if (null != mHeaderText) {
			mHeaderText.setText(mRefreshingLabel);
		}

		if (mUseIntrinsicAnimation) {
//			((AnimationDrawable) mHeaderImage.getDrawable()).start();
		    mHeaderImage.setVisibility(INVISIBLE);
		} else {
			// Now call the callback
//			refreshingImpl();
		    mHeaderImage.clearAnimation();
	        mHeaderImage.setVisibility(View.INVISIBLE);
	        mHeaderProgress.setVisibility(View.VISIBLE);
		}

//		if (null != mSubHeaderText) {
//			mSubHeaderText.setVisibility(View.GONE);
//		}
	}

	public final void releaseToRefresh() {
		if (null != mHeaderText) {
			mHeaderText.setText(mReleaseLabel);
		}

		// Now call the callback
		releaseToRefreshImpl();
	}

	public final void reset() {
		if (null != mHeaderText) {
			mHeaderText.setText(mPullLabel);
		}
		mHeaderImage.setVisibility(View.VISIBLE);

		if (mUseIntrinsicAnimation) {
			((AnimationDrawable) mHeaderImage.getDrawable()).stop();
		} else {
			// Now call the callback
//			resetImpl();
		    mHeaderImage.clearAnimation();
	        mHeaderProgress.setVisibility(View.GONE);
	        mHeaderImage.setVisibility(View.VISIBLE);
		}

		if (null != mSubHeaderText) {
			if (TextUtils.isEmpty(mSubHeaderText.getText())) {
				mSubHeaderText.setVisibility(View.GONE);
			} else {
				mSubHeaderText.setVisibility(View.VISIBLE);
			}
		}
	}

	@Override
	public void setLastUpdatedLabel(CharSequence label) {
		setSubHeaderText(label);
	}
	/**
	 * 设置次标题
	 * 
	 * <br>Created 2014-11-12 下午3:38:06
	 * @param label CharSequence
	 * @author       chenqian
	 */
	public void setSubHeaderTitleText(CharSequence label) {
		if (null != mSubHeaderTitle) {
			if (TextUtils.isEmpty(label)) {
				mSubHeaderTitle.setText("");
			} else {
				mSubHeaderTitle.setText(label);

				// Only set it to Visible if we're GONE, otherwise VISIBLE will
				// be set soon
				if (View.GONE == mSubHeaderTitle.getVisibility()) {
					mSubHeaderTitle.setVisibility(View.VISIBLE);
				}
			}
		}
	}

	public final void setLoadingDrawable(Drawable imageDrawable) {
		// Set Drawable
		mHeaderImage.setImageDrawable(imageDrawable);
		mUseIntrinsicAnimation = (imageDrawable instanceof AnimationDrawable);

		// Now call the callback
		onLoadingDrawableSet(imageDrawable);
	}

	public void setPullLabel(CharSequence pullLabel) {
		mPullLabel = pullLabel;
	}

	public void setRefreshingLabel(CharSequence refreshingLabel) {
		mRefreshingLabel = refreshingLabel;
	}

	public void setReleaseLabel(CharSequence releaseLabel) {
		mReleaseLabel = releaseLabel;
	}

	@Override
	public void setTextTypeface(Typeface tf) {
        StarAppUtils.setViewTypeFace(mHeaderText, false);
//        mHeaderText.setTypeface(tf);
	}

	public final void showInvisibleViews() {
		if (View.INVISIBLE == mHeaderText.getVisibility()) {
			mHeaderText.setVisibility(View.VISIBLE);
		}
		if (View.INVISIBLE == mHeaderProgress.getVisibility()) {
			mHeaderProgress.setVisibility(View.VISIBLE);
		}
		if (View.INVISIBLE == mHeaderImage.getVisibility()) {
			mHeaderImage.setVisibility(View.VISIBLE);
		}
		if (View.INVISIBLE == mSubHeaderText.getVisibility()) {
			mSubHeaderText.setVisibility(View.VISIBLE);
		}
		if (View.INVISIBLE == mSubHeaderTitle.getVisibility()) {
		    mSubHeaderTitle.setVisibility(View.VISIBLE);
        }
	}

	/**
	 * Callbacks for derivative Layouts
	 */

	protected abstract int getDefaultDrawableResId();

	protected abstract void onLoadingDrawableSet(Drawable imageDrawable);

	protected abstract void onPullImpl(float scaleOfLayout);

	protected abstract void pullToRefreshImpl();

	protected abstract void refreshingImpl();

	protected abstract void releaseToRefreshImpl();

	protected abstract void resetImpl();

	private void setSubHeaderText(CharSequence label) {
		if (null != mSubHeaderText) {
			if (TextUtils.isEmpty(label)) {
				mSubHeaderText.setVisibility(View.GONE);
			} else {
				mSubHeaderText.setText(label);

				// Only set it to Visible if we're GONE, otherwise VISIBLE will
				// be set soon
				if (View.GONE == mSubHeaderText.getVisibility()) {
					mSubHeaderText.setVisibility(View.VISIBLE);
				}
			}
		}
	}

	private void setSubTextAppearance(int value) {
		if (null != mSubHeaderText) {
			mSubHeaderText.setTextAppearance(getContext(), value);
		}
	}

	private void setSubTextColor(ColorStateList color) {
		if (null != mSubHeaderText) {
			mSubHeaderText.setTextColor(color);
		}
	}

	private void setTextAppearance(int value) {
		if (null != mHeaderText) {
			mHeaderText.setTextAppearance(getContext(), value);
		}
		if (null != mSubHeaderText) {
			mSubHeaderText.setTextAppearance(getContext(), value);
		}
	}

	private void setTextColor(ColorStateList color) {
		if (null != mHeaderText) {
			mHeaderText.setTextColor(color);
		}
		if (null != mSubHeaderText) {
			mSubHeaderText.setTextColor(color);
		}
	}
	
	/**
     * 统一设置全部字体颜色
     * 
     * <br>Created 2014-8-13 下午4:55:22
     * @param color
     * @author       wangds
     */
    public void setTextColor(int color) {
        if (null != mHeaderText) {
            mHeaderText.setTextColor(color);
        }
        if (null != mSubHeaderText) {
            mSubHeaderText.setTextColor(color);
        }
        if (null != mSubHeaderTitle) {
            mSubHeaderTitle.setTextColor(color);
        }
    }
}
